use std::collections::{HashMap, VecDeque};
use crate::error::{Result, PipitError};
use crate::vm::{Instruction, Value, ClassDefinition, Module, ModuleRegistry, DestroyPoolTemplate};

// 语法分析器的词法单元枚举
#[derive(Debug, PartialEq, Clone)]
pub enum Token {
    // 关键字
    Let, Fn, If, Else, While, For, In, Return, Import, Export, From, As, True, False,
    Class, Struct, Goto, Self_, New, This, Extends, Implements,
    Try, Catch, Finally, Throw, Interface, Match, With, Async, Await, Yield, Not,
    // 操作符
    Plus, Minus, Multiply, Divide, Assign, Equal, NotEqual, Less, LessEqual, Greater, GreaterEqual,
    Dot, // 新增点操作符
    NullishCoalescing, // ?? 空值合并运算符
    OptionalChain, // ?. 可选链运算符
    And, // 逻辑与操作符
    Or, // 逻辑或操作符
    // 符号
    LeftParen, RightParen, LeftBrace, RightBrace, LeftBracket, RightBracket, Semicolon, Comma, Colon,
    // 标识符和字面量
    Identifier(String), Number(i32), Float(f64), StringLiteral(String), Boolean(bool), Null,
    // 模板字符串插值控制标记
    InterpolationStart, InterpolationEnd,
    // 特殊标记
    Eof, Newline
}

// 词法分析器
pub struct Lexer {
    source: String,
    position: usize,
    current_char: Option<char>,
    line: usize,
    column: usize
}

impl Lexer {
    // 方便外部直接把源分词为 Token 列表
    pub fn tokenize(source: &str) -> Result<Vec<Token>> {
        let mut lex = Lexer::new(source);
        let mut tokens = Vec::new();
        loop {
            let t = lex.next_token()?;
            tokens.push(t.clone());
            if t == Token::Eof { break; }
        }
        Ok(tokens)
    }
}

impl Lexer {
    pub fn new(source: &str) -> Self {
        let mut lexer = Lexer {
            source: source.to_string(),
            position: 0,
            current_char: None,
            line: 1,
            column: 0
        };
        lexer.advance();
        lexer
    }
    
    fn advance(&mut self) {
        if self.position < self.source.len() {
            self.current_char = self.source.chars().nth(self.position);
            self.position += 1;
            self.column += 1;
            if self.current_char == Some('\n') {
                self.line += 1;
                self.column = 0;
            }
        } else {
            self.current_char = None;
        }
    }
    
    fn peek(&self) -> Option<char> {
        if self.position < self.source.len() {
            self.source.chars().nth(self.position)
        } else {
            None
        }
    }

    // 内部 token 缓冲，用于在遇到字符串插值时一次生成多个 token
    fn token_buffer_pop(&mut self) -> Option<Token> {
        // 使用 source 的一个简单辅助缓存放置生成的 token
        // 这里我们把缓冲存到 source 的末尾标记区，不创建新的字段以最小改动
        // 实际上我们将使用一个隐式 buffer 存放在 source 中的特殊占位，这里简化为 None
        None
    }
    
    fn skip_whitespace(&mut self) {
        while let Some(c) = self.current_char {
            if c.is_whitespace() && c != '\n' {
                self.advance();
            } else {
                break;
            }
        }
    }
    
    fn skip_comment(&mut self) -> Result<()> {
        if self.current_char == Some('/') && self.peek() == Some('/') {
            while self.current_char.is_some() && self.current_char != Some('\n') {
                self.advance();
            }
            Ok(())
        } else {
            Err(PipitError::SyntaxError("Not a comment".to_string()))
        }
    }
    
    fn identifier(&mut self) -> Token {
        let mut result = String::new();
        while let Some(c) = self.current_char {
            if c.is_alphanumeric() || c == '_' {
                result.push(c);
                self.advance();
            } else {
                break;
            }
        }
        
        // 检查是否是关键字
        match result.as_str() {
            "let" => Token::Let,
            "fn" => Token::Fn,
            "if" => Token::If,
            "else" => Token::Else,
            "while" => Token::While,
            "for" => Token::For,
            "in" => Token::In,
            "return" => Token::Return,
            "import" => Token::Import,
            "export" => Token::Export,
            "from" => Token::From,
            "as" => Token::As,
            "true" => Token::Boolean(true),
            "false" => Token::Boolean(false),
            "null" => Token::Null,
            "class" => Token::Class,
            "struct" => Token::Struct,
            "goto" => Token::Goto,
            "self" => Token::Self_,
            "new" => Token::New,
            "this" => Token::This,
            "extends" => Token::Extends,
            "implements" => Token::Implements,
            "try" => Token::Try,
            "catch" => Token::Catch,
            "finally" => Token::Finally,
            "throw" => Token::Throw,
            "interface" => Token::Interface,
            "match" => Token::Match,
            "with" => Token::With,
            "async" => Token::Async,
            "await" => Token::Await,
            "yield" => Token::Yield,
            "not" => Token::Not,
            "and" => Token::And,
            "or" => Token::Or,
            _ => Token::Identifier(result)
        }
    }
    
    fn number(&mut self) -> Result<Token> {
        let mut result = String::new();
        let mut has_decimal = false;
        
        while let Some(c) = self.current_char {
            if c.is_digit(10) {
                result.push(c);
                self.advance();
            } else if c == '.' && !has_decimal {
                result.push(c);
                has_decimal = true;
                self.advance();
            } else {
                break;
            }
        }
        
        if has_decimal {
            match result.parse::<f64>() {
                Ok(value) => Ok(Token::Float(value)),
                Err(_) => Err(PipitError::SyntaxError(format!("Invalid number: {}", result)))
            }
        } else {
            match result.parse::<i32>() {
                Ok(value) => Ok(Token::Number(value)),
                Err(_) => Err(PipitError::SyntaxError(format!("Invalid integer: {}", result)))
            }
        }
    }
    
    fn string_literal(&mut self) -> Result<Token> {
        let quote_char = self.current_char.unwrap();
        self.advance(); // 跳过引号
        let mut result = String::new();
        let is_backtick = quote_char == '`';
        
        while let Some(c) = self.current_char {
            if c == quote_char {
                self.advance();
                return Ok(Token::StringLiteral(result));
            } else if c == '\\' {
                // 处理转义字符
                self.advance();
                if let Some(escaped) = self.current_char {
                    match escaped {
                        'n' => result.push('\n'),
                        't' => result.push('\t'),
                        '\\' => result.push('\\'),
                        '"' => result.push('"'),
                        '\'' => result.push('\''),
                        '`' => result.push('`'),
                        _ => result.push(escaped)
                    }
                    self.advance();
                }
            } else if is_backtick && c == '$' && self.peek() == Some('{') {
                // 处理反引号字符串中的${}插值表达式
                self.advance(); // 跳过$ 
                self.advance(); // 跳过{ 
                
                // 收集插值内部源直到匹配 '}'
                let mut interp_src = String::new();
                let mut brace_depth = 1;
                while let Some(ch) = self.current_char {
                    self.advance();
                    if ch == '{' {
                        brace_depth += 1;
                    } else if ch == '}' {
                        brace_depth -= 1;
                        if brace_depth == 0 { break; }
                    }
                    interp_src.push(ch);
                }

                // 在字符串文本中插入占位标记
                result.push_str("{{INTERPOLATION}}");

                // 把原始插值源码以特殊前缀放到结果中，Parser 会识别并解析
                result.push_str(&format!("__INTERP_SRC__:{}__END_INTERP__", interp_src));
            } else if !is_backtick && c == '{' && self.peek() == Some('{') {
                // 处理双引号字符串中的{{}}插值表达式（向后兼容）
                self.advance(); // 跳过第一个{ 
                self.advance(); // 跳过第二个{ 
                
                // 收集直到 '}}'
                let mut interp_src = String::new();
                while let Some(ch) = self.current_char {
                    if ch == '}' && self.peek() == Some('}') {
                        // consume both
                        self.advance();
                        self.advance();
                        break;
                    }
                    interp_src.push(ch);
                    self.advance();
                }
                result.push_str("{{INTERPOLATION}}");
                result.push_str(&format!("__INTERP_SRC__:{}__END_INTERP__", interp_src));
            } else {
                result.push(c);
                self.advance();
            }
        }
        
        Err(PipitError::SyntaxError(format!("Unterminated {} string", if is_backtick { "backtick" } else { "double-quoted" })))
    }
    
    // 解析字符串插值中的表达式
    fn parse_interpolation_expression(&mut self) -> Result<Box<ASTNode>> {
        // 不再由Lexer解析插值表达式
        Err(PipitError::SyntaxError("Lexer.parse_interpolation_expression should not be called".to_string()))
    }
    
    pub fn next_token(&mut self) -> Result<Token> {
        loop {
            self.skip_whitespace();
            
            if let Some(c) = self.current_char {
                // 尝试跳过注释
                if let Ok(_) = self.skip_comment() {
                    continue;
                }
                
                return match c {
                    '+' => {
                        self.advance();
                        Ok(Token::Plus)
                    },
                    '-' => {
                        self.advance();
                        Ok(Token::Minus)
                    },
                    '*' => {
                        self.advance();
                        Ok(Token::Multiply)
                    },
                    '/' => {
                        self.advance();
                        Ok(Token::Divide)
                    },
                    '=' => {
                        self.advance();
                        if self.current_char == Some('=') {
                            self.advance();
                            Ok(Token::Equal)
                        } else {
                            Ok(Token::Assign)
                        }
                    },
                    '!' => {
                        self.advance();
                        if self.current_char == Some('=') {
                            self.advance();
                            Ok(Token::NotEqual)
                        } else {
                            Err(PipitError::SyntaxError("Unexpected character '!'".to_string()))
                        }
                    },
                    '<' => {
                        self.advance();
                        if self.current_char == Some('=') {
                            self.advance();
                            Ok(Token::LessEqual)
                        } else {
                            Ok(Token::Less)
                        }
                    },
                    '>' => {
                        self.advance();
                        if self.current_char == Some('=') {
                            self.advance();
                            Ok(Token::GreaterEqual)
                        } else {
                            Ok(Token::Greater)
                        }
                    },
                    '.' => {
                        self.advance();
                        Ok(Token::Dot)
                    },
                    '(' => {
                        self.advance();
                        Ok(Token::LeftParen)
                    },
                    ')' => {
                        self.advance();
                        Ok(Token::RightParen)
                    },
                    '{' => {
                        self.advance();
                        Ok(Token::LeftBrace)
                    },
                    '}' => {
                        self.advance();
                        Ok(Token::RightBrace)
                    },
                    '[' => {
                        self.advance();
                        Ok(Token::LeftBracket)
                    },
                    ']' => {
                        self.advance();
                        Ok(Token::RightBracket)
                    },
                    ';' => {
                        self.advance();
                        Ok(Token::Semicolon)
                    },
                    ',' => {
                        self.advance();
                        Ok(Token::Comma)
                    },
                    ':' => {
                        self.advance();
                        Ok(Token::Colon)
                    },
                    '?' => {
                        self.advance();
                        if let Some(next_c) = self.current_char {
                            if next_c == '?' {
                                self.advance();
                                Ok(Token::NullishCoalescing) // ?? 空值合并运算符
                            } else if next_c == '.' {
                                self.advance();
                                Ok(Token::OptionalChain) // ?. 可选链运算符
                            } else {
                                Err(PipitError::SyntaxError("Unexpected character after '?'".to_string()))
                            }
                        } else {
                            Err(PipitError::SyntaxError("Unexpected end of input after '?'".to_string()))
                        }
                    },
                    '"' | '`' => self.string_literal(),
                    '\n' => {
                        self.advance();
                        Ok(Token::Newline)
                    },
                    _ => {
                        if c.is_alphabetic() || c == '_' {
                            Ok(self.identifier())
                        } else if c.is_digit(10) {
                            self.number()
                        } else {
                            Err(PipitError::SyntaxError(format!("Unexpected character '{}'", c)))
                        }
                    }
                };
            } else {
                return Ok(Token::Eof);
            }
        }
    }
}

#[derive(Clone)]
pub enum ASTNode {
    Program(Vec<Box<ASTNode>>),
    FunctionDeclaration(String, Vec<String>, Box<ASTNode>),
    ClassDeclaration(String, Vec<(String, Vec<String>, Box<ASTNode>)>, HashMap<String, Box<ASTNode>>),
    StructDeclaration(String, Vec<String>, HashMap<String, Box<ASTNode>>),
    VariableDeclaration(String, Box<ASTNode>),
    AssignStatement(String, Box<ASTNode>),
    ReturnStatement(Box<ASTNode>),
    IfStatement(Box<ASTNode>, Box<ASTNode>, Option<Box<ASTNode>>),
    WhileStatement(Box<ASTNode>, Box<ASTNode>),
    ForStatement(String, Box<ASTNode>, Box<ASTNode>, Box<ASTNode>),
    GotoStatement(String),
    LabelStatement(String),
    Block(Vec<Box<ASTNode>>),
    BinaryExpression(Box<ASTNode>, Token, Box<ASTNode>),
    UnaryExpression(Token, Box<ASTNode>),
    FunctionCall(String, Vec<Box<ASTNode>>),
    MethodCall(Box<ASTNode>, String, Vec<Box<ASTNode>>),
    ArrayLiteral(Vec<Box<ASTNode>>),
    ArrayAccess(Box<ASTNode>, Box<ASTNode>),
    ArrayAssign(String, Box<ASTNode>, Box<ASTNode>),
    StructLiteral(String, HashMap<String, Box<ASTNode>>),
    StructAccess(Box<ASTNode>, String),
    StructAssign(String, String, Box<ASTNode>),
    ClassInstantiation(String, Vec<Box<ASTNode>>),
    OptionalChainAccess(Box<ASTNode>, String), // 可选链访问: obj?.prop
    OptionalChainArrayAccess(Box<ASTNode>, Box<ASTNode>), // 可选链数组访问: obj?.[index]
    TryStatement(Box<ASTNode>, Box<ASTNode>, Option<Box<ASTNode>>), // try块, catch块, finally块
    CatchStatement(String, Box<ASTNode>), // 异常变量名, catch块
    ThrowStatement(Box<ASTNode>), // 抛出的表达式
    ImportStatement(Vec<String>, String, Option<String>), // 导入项, 模块路径, 别名
    ExportStatement(Vec<String>, Option<String>), // 导出项, 可选模块名
    Identifier(String),
    Literal(Value)
}

// 语法分析器
pub struct Parser {
    lexer: Lexer,
    current_token: Token,
    tokens: VecDeque<Token>,
    lookahead: Token,
    next_function_index: u32
}

impl Parser {
    pub fn new(source: &str) -> Result<Self> {
        let mut lexer = Lexer::new(source);
        let current_token = lexer.next_token()?;
        let lookahead = lexer.next_token()?;
        
        let mut tokens = VecDeque::new();
        tokens.push_back(current_token.clone());
        tokens.push_back(lookahead.clone());
        
        Ok(Parser {
            lexer,
            current_token,
            tokens,
            lookahead,
            next_function_index: 0
        })
    }

    /// 从一个已分词的 Token 向量创建 Parser（用于子解析）
    pub fn from_tokens(tokens: Vec<Token>) -> Result<Self> {
        let mut deque = VecDeque::new();
        for t in tokens.iter().take(2) {
            deque.push_back(t.clone());
        }
        let current = deque.pop_front().unwrap_or(Token::Eof);
        let lookahead = deque.pop_front().unwrap_or(Token::Eof);
        Ok(Parser {
            lexer: Lexer::new("") , // 占位，不会使用 lexer.next_token 在子解析器中
            current_token: current,
            tokens: VecDeque::from(tokens),
            lookahead,
            next_function_index: 0
        })
    }

    /// 使用子解析器从源字符串解析为单个表达式 AST
    pub fn parse_from_source(source: &str) -> Result<Box<ASTNode>> {
        let tokens = Lexer::tokenize(source)?;
        let mut p = Parser::from_tokens(tokens)?;
        p.parse_expression()
    }
    
    fn advance(&mut self) -> Result<()> {
        self.current_token = self.lookahead.clone();
        self.lookahead = self.lexer.next_token()?;
        self.tokens.pop_front();
        self.tokens.push_back(self.lookahead.clone());
        Ok(())
    }
    
    fn consume(&mut self, expected: Token) -> Result<()> {
        if self.current_token == expected {
            self.advance()
        } else {
            Err(PipitError::CompileError(format!("Expected {:?}, got {:?}", expected, self.current_token)))
        }
    }
    
    pub fn parse(&mut self) -> Result<Box<ASTNode>> {
        let mut statements = Vec::new();
        
        while self.current_token != Token::Eof {
            if self.current_token == Token::Newline {
                self.advance()?;
                continue;
            }
            
            statements.push(self.parse_statement()?);
        }
        
        Ok(Box::new(ASTNode::Program(statements)))
    }
    
    fn parse_statement(&mut self) -> Result<Box<ASTNode>> {
        match &self.current_token {
            Token::Let => self.parse_variable_declaration(),
            Token::Fn => self.parse_function_declaration(),
            Token::Class => self.parse_class_declaration(),
            Token::Struct => self.parse_struct_declaration(),
            Token::Goto => self.parse_goto_statement(),
            Token::Return => self.parse_return_statement(),
            Token::If => self.parse_if_statement(),
            Token::While => self.parse_while_statement(),
            Token::For => self.parse_for_statement(),
            Token::Try => self.parse_try_statement(),
            Token::Throw => self.parse_throw_statement(),
            Token::Import => self.parse_import_statement(),
            Token::Export => self.parse_export_statement(),
            Token::LeftBrace => self.parse_block(),
            Token::Identifier(name) => {
                // 检查是否是标签定义
                if let Token::Colon = self.lookahead {
                    return self.parse_label_statement(name.clone());
                }
                // 检查是否是数组赋值
                if let Token::LeftBracket = self.lookahead {
                    self.parse_array_assign(name.clone())
                } else if let Token::Assign = self.lookahead {
                    self.parse_assign_statement(name.clone())
                } else if let Token::LeftParen = self.lookahead {
                    // 函数调用
                    self.parse_function_call(name.clone())
                } else if let Token::Dot = self.lookahead {
                    // 方法调用或字段访问
                    self.parse_method_call_or_field_access(Box::new(ASTNode::Identifier(name.clone())), false)
                } else {
                    Err(PipitError::CompileError(format!("Unexpected identifier: {}", name)))
                }
            },
            _ => self.parse_expression()
        }
    }
    
    fn parse_variable_declaration(&mut self) -> Result<Box<ASTNode>> {
        self.consume(Token::Let)?;
        
        // 检查是否是解构赋值（数组）
        if self.current_token == Token::LeftBracket {
            return self.parse_array_destructuring();
        }
        // 检查是否是解构赋值（对象）
        else if self.current_token == Token::LeftBrace {
            return self.parse_object_destructuring();
        }
        // 普通变量声明
        else if let Token::Identifier(name) = &self.current_token {
            let var_name = name.clone();
            self.consume(Token::Identifier(var_name.clone()))?;
            self.consume(Token::Assign)?;
            let expr = self.parse_expression()?;
            
            Ok(Box::new(ASTNode::VariableDeclaration(var_name, expr)))
        } else {
            Err(PipitError::CompileError("Expected identifier after 'let'".to_string()))
        }
    }
    
    // 解析数组解构赋值
    fn parse_array_destructuring(&mut self) -> Result<Box<ASTNode>> {
        self.consume(Token::LeftBracket)?;
        
        let mut variables = Vec::new();
        
        // 解析数组中的变量列表
        while self.current_token != Token::RightBracket {
            if let Token::Identifier(name) = &self.current_token {
                variables.push(name.clone());
                self.consume(Token::Identifier(name.clone()))?;
            }
            
            if self.current_token == Token::Comma {
                self.consume(Token::Comma)?;
            }
        }
        
        self.consume(Token::RightBracket)?;
        self.consume(Token::Assign)?;
        let expr = self.parse_expression()?;
        
        // 创建多个变量声明语句
        let mut statements = Vec::new();
        for (i, var_name) in variables.iter().enumerate() {
            // 生成表达式: expr[i]
            let array_access = Box::new(ASTNode::ArrayAccess(
                expr.clone(), 
                Box::new(ASTNode::Literal(Value::Integer(i as i32)))
            ));
            statements.push(Box::new(ASTNode::VariableDeclaration(var_name.clone(), array_access)));
        }
        
        Ok(Box::new(ASTNode::Block(statements)))
    }
    
    // 解析对象解构赋值
    fn parse_object_destructuring(&mut self) -> Result<Box<ASTNode>> {
        self.consume(Token::LeftBrace)?;
        
        let mut properties = Vec::new();
        
        // 解析对象中的属性列表
        while self.current_token != Token::RightBrace {
            if let Token::Identifier(name) = &self.current_token {
                properties.push(name.clone());
                self.consume(Token::Identifier(name.clone()))?;
            }
            
            if self.current_token == Token::Comma {
                self.consume(Token::Comma)?;
            }
        }
        
        self.consume(Token::RightBrace)?;
        self.consume(Token::Assign)?;
        let expr = self.parse_expression()?;
        
        // 创建多个变量声明语句
        let mut statements = Vec::new();
        for prop_name in properties {
            // 生成表达式: expr.prop_name
            let field_access = Box::new(ASTNode::StructAccess(
                expr.clone(), 
                prop_name.clone()
            ));
            statements.push(Box::new(ASTNode::VariableDeclaration(prop_name, field_access)));
        }
        
        Ok(Box::new(ASTNode::Block(statements)))
    }
    
    fn parse_assign_statement(&mut self, name: String) -> Result<Box<ASTNode>> {
        self.consume(Token::Identifier(name.clone()))?;
        self.consume(Token::Assign)?;
        let expr = self.parse_expression()?;
        
        Ok(Box::new(ASTNode::AssignStatement(name, expr)))
    }
    
    fn parse_function_declaration(&mut self) -> Result<Box<ASTNode>> {
        self.consume(Token::Fn)?;
        
        if let Token::Identifier(name) = &self.current_token {
            let fn_name = name.clone();
            self.consume(Token::Identifier(fn_name.clone()))?;
            self.consume(Token::LeftParen)?;
            
            let mut params = Vec::new();
            if let Token::Identifier(param_name) = &self.current_token {
                params.push(param_name.clone());
                self.consume(Token::Identifier(param_name.clone()))?;
                
                while self.current_token == Token::Comma {
                    self.consume(Token::Comma)?;
                    if let Token::Identifier(next_param) = &self.current_token {
                        params.push(next_param.clone());
                        self.consume(Token::Identifier(next_param.clone()))?;
                    } else {
                        return Err(PipitError::CompileError("Expected parameter name".to_string()));
                    }
                }
            }
            
            self.consume(Token::RightParen)?;
            let body = self.parse_block()?;
            
            Ok(Box::new(ASTNode::FunctionDeclaration(fn_name, params, body)))
        } else {
            Err(PipitError::CompileError("Expected function name".to_string()))
        }
    }
    
    fn parse_function_call(&mut self, name: String) -> Result<Box<ASTNode>> {
        self.consume(Token::Identifier(name.clone()))?;
        self.consume(Token::LeftParen)?;
        
        let mut args = Vec::new();
        if self.current_token != Token::RightParen {
            args.push(self.parse_expression()?);
            
            while self.current_token == Token::Comma {
                self.consume(Token::Comma)?;
                args.push(self.parse_expression()?);
            }
        }
        
        self.consume(Token::RightParen)?;
        Ok(Box::new(ASTNode::FunctionCall(name, args)))
    }
    
    fn parse_return_statement(&mut self) -> Result<Box<ASTNode>> {
        self.consume(Token::Return)?;
        let expr = self.parse_expression()?;
        Ok(Box::new(ASTNode::ReturnStatement(expr)))
    }
    
    fn parse_if_statement(&mut self) -> Result<Box<ASTNode>> {
        self.consume(Token::If)?;
        self.consume(Token::LeftParen)?;
        let condition = self.parse_expression()?;
        self.consume(Token::RightParen)?;
        let then_branch = self.parse_block()?;
        
        let else_branch = if self.current_token == Token::Else {
            self.consume(Token::Else)?;
            Some(self.parse_block()?)
        } else {
            None
        };
        
        Ok(Box::new(ASTNode::IfStatement(condition, then_branch, else_branch)))
    }
    
    fn parse_while_statement(&mut self) -> Result<Box<ASTNode>> {
        self.consume(Token::While)?;
        self.consume(Token::LeftParen)?;
        let condition = self.parse_expression()?;
        self.consume(Token::RightParen)?;
        let body = self.parse_block()?;
        
        Ok(Box::new(ASTNode::WhileStatement(condition, body)))
    }
    
    fn parse_for_statement(&mut self) -> Result<Box<ASTNode>> {
        self.consume(Token::For)?;
        self.consume(Token::LeftParen)?;
        
        if let Token::Identifier(var_name) = &self.current_token {
            let variable = var_name.clone();
            self.consume(Token::Identifier(variable.clone()))?;
            self.consume(Token::In)?;
            let iterable = self.parse_expression()?;
            self.consume(Token::RightParen)?;
            let body = self.parse_block()?;
            Ok(Box::new(ASTNode::ForStatement(variable, iterable, Box::new(ASTNode::Literal(Value::Integer(0))), body)))
        } else {
            Err(PipitError::CompileError("Expected identifier in for loop".to_string()))
        }
    }

    fn parse_class_declaration(&mut self) -> Result<Box<ASTNode>> {
        self.consume(Token::Class)?;
        
        if let Token::Identifier(class_name) = &self.current_token {
            let name = class_name.clone();
            self.consume(Token::Identifier(name.clone()))?;
            self.consume(Token::LeftBrace)?;
            
            let mut methods = Vec::new();
            let mut fields = HashMap::new();
            
            while self.current_token != Token::RightBrace && self.current_token != Token::Eof {
                if self.current_token == Token::Newline {
                    self.advance()?;
                    continue;
                }
                
                if let Token::Fn = self.current_token {
                    let method = self.parse_method_declaration()?;
                    if let ASTNode::FunctionDeclaration(name, params, body) = *method {
                        methods.push((name, params, body));
                    }
                } else if let Token::Let = self.current_token {
                    let field = self.parse_field_declaration()?;
                    if let ASTNode::VariableDeclaration(name, value) = *field {
                        fields.insert(name, value);
                    }
                } else {
                    self.advance()?; // 跳过未知标记
                }
            }
            
            self.consume(Token::RightBrace)?;
            Ok(Box::new(ASTNode::ClassDeclaration(name, methods, fields)))
        } else {
            Err(PipitError::CompileError("Expected class name".to_string()))
        }
    }

    fn parse_struct_declaration(&mut self) -> Result<Box<ASTNode>> {
        self.consume(Token::Struct)?;
        
        if let Token::Identifier(struct_name) = &self.current_token {
            let name = struct_name.clone();
            self.consume(Token::Identifier(name.clone()))?;
            self.consume(Token::LeftBrace)?;
            
            let mut fields = Vec::new();
            let mut defaults = HashMap::new();
            
            while self.current_token != Token::RightBrace && self.current_token != Token::Eof {
                if self.current_token == Token::Newline {
                    self.advance()?;
                    continue;
                }
                
                if let Token::Identifier(field_name) = &self.current_token {
                    let name = field_name.clone();
                    self.consume(Token::Identifier(name.clone()))?;
                    
                    if self.current_token == Token::Assign {
                        self.consume(Token::Assign)?;
                        let default_value = self.parse_expression()?;
                        defaults.insert(name.clone(), default_value);
                    }
                    
                    fields.push(name);
                    
                    if self.current_token == Token::Comma {
                        self.consume(Token::Comma)?;
                    }
                } else {
                    self.advance()?;
                }
            }
            
            self.consume(Token::RightBrace)?;
            Ok(Box::new(ASTNode::StructDeclaration(name, fields, defaults)))
        } else {
            Err(PipitError::CompileError("Expected struct name".to_string()))
        }
    }

    fn parse_method_declaration(&mut self) -> Result<Box<ASTNode>> {
        self.parse_function_declaration() // 复用函数声明解析
    }

    fn parse_field_declaration(&mut self) -> Result<Box<ASTNode>> {
        self.parse_variable_declaration() // 复用变量声明解析
    }

    fn parse_goto_statement(&mut self) -> Result<Box<ASTNode>> {
        self.consume(Token::Goto)?;
        
        if let Token::Identifier(label) = &self.current_token {
            let label_name = label.clone();
            self.consume(Token::Identifier(label_name.clone()))?;
            Ok(Box::new(ASTNode::GotoStatement(label_name)))
        } else {
            Err(PipitError::CompileError("Expected label name".to_string()))
        }
    }
    
    fn parse_try_statement(&mut self) -> Result<Box<ASTNode>> {
        self.consume(Token::Try)?;
        let try_block = self.parse_block()?;
        
        let mut catch_block = None;
        let mut finally_block = None;
        
        // 解析catch块
        if self.current_token == Token::Catch {
            self.consume(Token::Catch)?;
            self.consume(Token::LeftParen)?;
            
            let error_var = if let Token::Identifier(name) = &self.current_token {
                let var_name = name.clone();
                self.consume(Token::Identifier(var_name.clone()))?;
                var_name
            } else {
                return Err(PipitError::CompileError("Expected error variable name in catch block".to_string()));
            };
            
            self.consume(Token::RightParen)?;
            let catch_body = self.parse_block()?;
            catch_block = Some(Box::new(ASTNode::CatchStatement(error_var, catch_body)));
        }
        
        // 解析finally块
        if self.current_token == Token::Finally {
            self.consume(Token::Finally)?;
            finally_block = Some(self.parse_block()?);
        }
        
        Ok(Box::new(ASTNode::TryStatement(try_block.clone(), catch_block.unwrap_or(try_block.clone()), finally_block)))
    }
    
    fn parse_throw_statement(&mut self) -> Result<Box<ASTNode>> {
        self.consume(Token::Throw)?;
        let expr = self.parse_expression()?;
        Ok(Box::new(ASTNode::ThrowStatement(expr)))
    }
    
    fn parse_import_statement(&mut self) -> Result<Box<ASTNode>> {
        self.consume(Token::Import)?;
        
        let mut imports = Vec::new();
        let mut module_path = String::new();
        let mut alias = None;
        
        // 解析导入项列表
        if self.current_token == Token::LeftBrace {
            self.consume(Token::LeftBrace)?;
            
            while self.current_token != Token::RightBrace {
                if let Token::Identifier(name) = &self.current_token {
                    imports.push(name.clone());
                    self.consume(Token::Identifier(name.clone()))?;
                }
                
                if self.current_token == Token::Comma {
                    self.consume(Token::Comma)?;
                }
            }
            
            self.consume(Token::RightBrace)?;
        } else if let Token::Identifier(name) = &self.current_token {
            // 导入默认项
            imports.push(name.clone());
            self.consume(Token::Identifier(name.clone()))?;
        }
        
        self.consume(Token::From)?;
        
        // 解析模块路径
        if let Token::StringLiteral(path) = &self.current_token {
            module_path = path.clone();
            self.consume(Token::StringLiteral(path.clone()))?;
        } else {
            return Err(PipitError::CompileError("Expected module path string".to_string()));
        }
        
        // 解析别名
        if self.current_token == Token::As {
            self.consume(Token::As)?;
            if let Token::Identifier(name) = &self.current_token {
                alias = Some(name.clone());
                self.consume(Token::Identifier(name.clone()))?;
            } else {
                return Err(PipitError::CompileError("Expected alias name".to_string()));
            }
        }
        
        Ok(Box::new(ASTNode::ImportStatement(imports, module_path, alias)))
    }
    
    fn parse_export_statement(&mut self) -> Result<Box<ASTNode>> {
        self.consume(Token::Export)?;
        
        let mut exports = Vec::new();
        let mut module_name = None;
        
        // 解析导出项列表
        if self.current_token == Token::LeftBrace {
            self.consume(Token::LeftBrace)?;
            
            while self.current_token != Token::RightBrace {
                if let Token::Identifier(name) = &self.current_token {
                    exports.push(name.clone());
                    self.consume(Token::Identifier(name.clone()))?;
                }
                
                if self.current_token == Token::Comma {
                    self.consume(Token::Comma)?;
                }
            }
            
            self.consume(Token::RightBrace)?;
        } else if let Token::Identifier(name) = &self.current_token {
            // 导出单个标识符
            exports.push(name.clone());
            self.consume(Token::Identifier(name.clone()))?;
        }
        
        // 解析可选的模块名
        if self.current_token == Token::As {
            self.consume(Token::As)?;
            if let Token::Identifier(name) = &self.current_token {
                module_name = Some(name.clone());
                self.consume(Token::Identifier(name.clone()))?;
            } else {
                return Err(PipitError::CompileError("Expected module name".to_string()));
            }
        }
        
        Ok(Box::new(ASTNode::ExportStatement(exports, module_name)))
    }

    fn parse_label_statement(&mut self, name: String) -> Result<Box<ASTNode>> {
        self.consume(Token::Identifier(name.clone()))?;
        self.consume(Token::Colon)?;
        Ok(Box::new(ASTNode::LabelStatement(name)))
    }

    fn parse_method_call_or_field_access(&mut self, object: Box<ASTNode>, is_optional: bool) -> Result<Box<ASTNode>> {
        // 消费点操作符或可选链操作符
        if is_optional {
            self.consume(Token::OptionalChain)?;
        } else {
            self.consume(Token::Dot)?;
        }
        
        if let Token::Identifier(field_name) = &self.current_token {
            let name = field_name.clone();
            self.consume(Token::Identifier(name.clone()))?;
            
            // 检查是否是方法调用
            if self.current_token == Token::LeftParen {
                // 方法调用
                self.consume(Token::LeftParen)?;
                
                let mut args = Vec::new();
                if self.current_token != Token::RightParen {
                    args.push(self.parse_expression()?);
                    
                    while self.current_token == Token::Comma {
                        self.consume(Token::Comma)?;
                        args.push(self.parse_expression()?);
                    }
                }
                
                self.consume(Token::RightParen)?;
                if is_optional {
                    // 可选链方法调用
                    Ok(Box::new(ASTNode::OptionalChainAccess(object, name)))
                } else {
                    // 普通方法调用
                    Ok(Box::new(ASTNode::MethodCall(object, name, args)))
                }
            } else {
                // 字段访问
                if is_optional {
                    // 可选链字段访问
                    Ok(Box::new(ASTNode::OptionalChainAccess(object, name)))
                } else {
                    // 普通字段访问
                    Ok(Box::new(ASTNode::StructAccess(object, name)))
                }
            }
        } else {
            Err(PipitError::CompileError("Expected identifier after dot or optional chain".to_string()))
        }
    }
    
    fn parse_block(&mut self) -> Result<Box<ASTNode>> {
        self.consume(Token::LeftBrace)?;
        let mut statements = Vec::new();
        
        while self.current_token != Token::RightBrace && self.current_token != Token::Eof {
            if self.current_token == Token::Newline {
                self.advance()?;
                continue;
            }
            
            statements.push(self.parse_statement()?);
        }
        
        self.consume(Token::RightBrace)?;
        Ok(Box::new(ASTNode::Block(statements)))
    }
    
    fn parse_expression(&mut self) -> Result<Box<ASTNode>> {
        match self.current_token {
            Token::LeftBracket => self.parse_array_literal(),
            _ => self.parse_array_access()
        }
    }
    
    fn parse_array_access(&mut self) -> Result<Box<ASTNode>> {
        let left = self.parse_assignment()?;
        
        if self.current_token == Token::LeftBracket {
            self.consume(Token::LeftBracket)?;
            let index = self.parse_expression()?;
            self.consume(Token::RightBracket)?;
            
            Ok(Box::new(ASTNode::ArrayAccess(left, index)))
        } else if let ASTNode::OptionalChainAccess(ref obj, _) = *left {
            // 检查是否是可选链数组访问: obj?.prop?.[index]
            if self.current_token == Token::LeftBracket {
                self.consume(Token::LeftBracket)?;
                let index = self.parse_expression()?;
                self.consume(Token::RightBracket)?;
                
                Ok(Box::new(ASTNode::OptionalChainArrayAccess(obj.clone(), index)))
            } else {
                Ok(left)
            }
        } else {
            Ok(left)
        }
    }
    
    fn parse_array_literal(&mut self) -> Result<Box<ASTNode>> {
        self.consume(Token::LeftBracket)?;
        let mut elements = Vec::new();
        
        if self.current_token != Token::RightBracket {
            elements.push(self.parse_expression()?);
            
            while self.current_token == Token::Comma {
                self.consume(Token::Comma)?;
                elements.push(self.parse_expression()?);
            }
        }
        
        self.consume(Token::RightBracket)?;
        Ok(Box::new(ASTNode::ArrayLiteral(elements)))
    }
    
    fn parse_array_assign(&mut self, name: String) -> Result<Box<ASTNode>> {
        self.consume(Token::Identifier(name.clone()))?;
        self.consume(Token::LeftBracket)?;
        let index = self.parse_expression()?;
        self.consume(Token::RightBracket)?;
        self.consume(Token::Assign)?;
        let value = self.parse_expression()?;
        
        Ok(Box::new(ASTNode::ArrayAssign(name, index, value)))
    }
    
    fn parse_assignment(&mut self) -> Result<Box<ASTNode>> {
        let left = self.parse_logical_or()?;
        
        if self.current_token == Token::Assign {
            self.consume(Token::Assign)?;
            let right = self.parse_assignment()?;
            
            if let ASTNode::Identifier(name) = *left {
                return Ok(Box::new(ASTNode::AssignStatement(name, right)));
            } else {
                return Err(PipitError::CompileError("Invalid assignment target".to_string()));
            }
        }
        
        Ok(left)
    }
    
    fn parse_logical_or(&mut self) -> Result<Box<ASTNode>> {
        let mut left = self.parse_logical_and()?;
        
        while self.current_token == Token::Or || self.current_token == Token::NullishCoalescing {
            let operator = self.current_token.clone();
            match &operator {
                Token::Or => {
                    self.consume(Token::Or)?;
                },
                Token::NullishCoalescing => {
                    self.consume(Token::NullishCoalescing)?;
                },
                _ => unreachable!()
            }
            let right = self.parse_logical_and()?;
            left = Box::new(ASTNode::BinaryExpression(left, operator, right));
        }
        
        Ok(left)
    }
    
    fn parse_logical_and(&mut self) -> Result<Box<ASTNode>> {
        let mut left = self.parse_equality()?;
        
        while self.current_token == Token::And {
            self.consume(Token::And)?;
            let right = self.parse_equality()?;
            left = Box::new(ASTNode::BinaryExpression(left, Token::And, right));
        }
        
        Ok(left)
    }
    
    fn parse_equality(&mut self) -> Result<Box<ASTNode>> {
        let mut left = self.parse_comparison()?;
        
        while self.current_token == Token::Equal || self.current_token == Token::NotEqual {
            let operator = self.current_token.clone();
            self.advance()?;
            let right = self.parse_comparison()?;
            left = Box::new(ASTNode::BinaryExpression(left, operator, right));
        }
        
        Ok(left)
    }
    
    fn parse_comparison(&mut self) -> Result<Box<ASTNode>> {
        let mut left = self.parse_addition()?;
        
        while self.current_token == Token::Less || 
              self.current_token == Token::LessEqual || 
              self.current_token == Token::Greater || 
              self.current_token == Token::GreaterEqual {
            let operator = self.current_token.clone();
            self.advance()?;
            let right = self.parse_addition()?;
            left = Box::new(ASTNode::BinaryExpression(left, operator, right));
        }
        
        Ok(left)
    }
    
    fn parse_addition(&mut self) -> Result<Box<ASTNode>> {
        let mut left = self.parse_multiplication()?;
        
        while self.current_token == Token::Plus || self.current_token == Token::Minus {
            let operator = self.current_token.clone();
            self.advance()?;
            let right = self.parse_multiplication()?;
            left = Box::new(ASTNode::BinaryExpression(left, operator, right));
        }
        
        Ok(left)
    }
    
    fn parse_multiplication(&mut self) -> Result<Box<ASTNode>> {
        let mut left = self.parse_unary()?;
        
        while self.current_token == Token::Multiply || self.current_token == Token::Divide {
            let operator = self.current_token.clone();
            self.advance()?;
            let right = self.parse_unary()?;
            left = Box::new(ASTNode::BinaryExpression(left, operator, right));
        }
        
        Ok(left)
    }
    
    fn parse_unary(&mut self) -> Result<Box<ASTNode>> {
        if self.current_token == Token::Minus {
            self.advance()?;
            let expr = self.parse_unary()?;
            return Ok(Box::new(ASTNode::UnaryExpression(Token::Minus, expr)));
        } else if self.current_token == Token::Not {
            self.advance()?;
            let expr = self.parse_unary()?;
            return Ok(Box::new(ASTNode::UnaryExpression(Token::Not, expr)));
        }
        
        self.parse_primary()
    }
    
    fn parse_primary(&mut self) -> Result<Box<ASTNode>> {
        // 克隆current_token以避免可变借用冲突
        let current_token_clone = self.current_token.clone();
        
        match current_token_clone {
            Token::Number(n) => {
                self.advance()?;
                Ok(Box::new(ASTNode::Literal(Value::Integer(n))))
            },
            Token::Float(f) => {
                self.advance()?;
                Ok(Box::new(ASTNode::Literal(Value::Float(f))))
            },
            Token::StringLiteral(s) => {
                self.advance()?;
                // 检查字符串中是否包含插值表达式
                if s.contains("{{INTERPOLATION}}") {
                    // 处理字符串插值，将其转换为字符串拼接表达式
                    self.process_string_interpolation(s)
                } else {
                    Ok(Box::new(ASTNode::Literal(Value::String(s))))
                }
            },
            Token::Boolean(b) => {
                self.advance()?;
                Ok(Box::new(ASTNode::Literal(Value::Boolean(b))))
            },
            Token::Null => {
                self.advance()?;
                Ok(Box::new(ASTNode::Literal(Value::Null)))
            },
            Token::Fn => {
                // 支持表达式层面的箭头函数： fn(params) => expr
                return self.parse_arrow_function();
            }
            Token::Identifier(name) => {
                self.advance()?;
                
                // 检查是否是字段访问或方法调用 (普通点或可选链)
                let identifier = Box::new(ASTNode::Identifier(name.clone()));
                
                // 检查是否是函数调用
                if self.current_token == Token::LeftParen {
                    let mut args = Vec::new();
                    self.consume(Token::LeftParen)?;
                    
                    if self.current_token != Token::RightParen {
                        args.push(self.parse_expression()?);
                        
                        while self.current_token == Token::Comma {
                            self.consume(Token::Comma)?;
                            args.push(self.parse_expression()?);
                        }
                    }
                    
                    self.consume(Token::RightParen)?;
                    Ok(Box::new(ASTNode::FunctionCall(name, args)))
                } else if self.current_token == Token::Dot || self.current_token == Token::OptionalChain {
                    // 处理字段访问或方法调用
                    self.parse_method_call_or_field_access(identifier, self.current_token == Token::OptionalChain)
                } else {
                    Ok(identifier)
                }
            },
            Token::LeftParen => {
                self.consume(Token::LeftParen)?;
                let expr = self.parse_expression()?;
                self.consume(Token::RightParen)?;
                Ok(expr)
            },
            _ => Err(PipitError::CompileError(format!("Unexpected token: {:?}", self.current_token)))
        }
    } 
    
    // 解析箭头函数 (Lambda表达式)
    fn parse_arrow_function(&mut self) -> Result<Box<ASTNode>> {
        // 已经在调用处消费了 Token::Fn 或在此处确保消费
        if self.current_token == Token::Fn {
            self.consume(Token::Fn)?;
        }
        self.consume(Token::LeftParen)?;
        
        // 解析参数列表
        let mut params = Vec::new();
        while self.current_token != Token::RightParen {
            if let Token::Identifier(name) = &self.current_token {
                params.push(name.clone());
                self.consume(Token::Identifier(name.clone()))?;
            }
            
            if self.current_token == Token::Comma {
                self.consume(Token::Comma)?;
            }
        }
        
        self.consume(Token::RightParen)?;
        
        // 检查箭头符号 ('=>')，词法器会产出 Assign ('=') 然后 Greater ('>')
        if self.current_token != Token::Assign || self.lookahead != Token::Greater {
            return Err(PipitError::CompileError("Expected '=>' in arrow function".to_string()));
        }

        self.consume(Token::Assign)?;
        self.consume(Token::Greater)?;
        
        // 解析函数体（表达式）
        let body = self.parse_expression()?;
        
        // 为箭头函数生成一个唯一的名称
        let arrow_fn_name = format!("_lambda_{}", self.next_function_index);
        self.next_function_index += 1;
        
        // 创建函数声明节点
        let _fn_decl = Box::new(ASTNode::FunctionDeclaration(
            arrow_fn_name.clone(), 
            params, 
            Box::new(ASTNode::Block(vec![
                Box::new(ASTNode::ReturnStatement(body))
            ]))
        ));
        
        // 先将函数声明添加到当前作用域
        let fn_node = Box::new(ASTNode::FunctionCall(arrow_fn_name, Vec::new()));
        
        // 我们需要将函数声明添加到程序的顶部，这里简化处理，直接返回函数调用
        // 实际实现中应该将函数声明添加到当前作用域的语句列表中
        Ok(fn_node)
    }
    
    // 处理字符串插值
    fn process_string_interpolation(&mut self, s: String) -> Result<Box<ASTNode>> {
        // 检查字符串中是否包含插值标记
        if !s.contains("{{INTERPOLATION}}") {
            // 没有插值表达式
            return Ok(Box::new(ASTNode::Literal(Value::String(s))));
        }
        
    // 将字符串按插值标记分割
    let parts: Vec<&str> = s.split("{{INTERPOLATION}}").collect();
        
        // 如果只有一个部分且不包含插值标记，直接返回字符串字面量
        if parts.len() == 1 {
            return Ok(Box::new(ASTNode::Literal(Value::String(s))));
        }
        
        // 构建字符串拼接表达式：初始为第一个文本片段
        let mut concat_expr = Box::new(ASTNode::Literal(Value::String(parts[0].to_string())));

        for i in 1..parts.len() {
            let part = parts[i];
            // 如果 part 含有我们的特殊插值源码标记 __INTERP_SRC__:<src>__END_INTERP__
            if let Some(idx) = part.find("__INTERP_SRC__:") {
                // 提取插值源码
                if let Some(end_idx) = part.find("__END_INTERP__") {
                    let src = &part[(idx + "__INTERP_SRC__:".len())..end_idx];
                    // 解析插值表达式源为 AST
                    let expr_ast = Parser::parse_from_source(src)?;

                    // 拼接 previous + expr
                    concat_expr = Box::new(ASTNode::BinaryExpression(concat_expr, Token::Plus, expr_ast));

                    // 如果插值后还有文本，拼接文本
                    let trailing = &part[(end_idx + "__END_INTERP__".len())..];
                    if !trailing.is_empty() {
                        concat_expr = Box::new(ASTNode::BinaryExpression(
                            concat_expr,
                            Token::Plus,
                            Box::new(ASTNode::Literal(Value::String(trailing.to_string())))
                        ));
                    }
                    continue;
                }
            }

            // 否则该部分是普通文本，直接与之前拼接
            concat_expr = Box::new(ASTNode::BinaryExpression(
                concat_expr,
                Token::Plus,
                Box::new(ASTNode::Literal(Value::String(part.to_string())))
            ));
        }

        Ok(concat_expr)
    }
}

// 编译器
pub struct Compiler {
    bytecode: Vec<Instruction>,
    variables: HashMap<String, i32>,         // 变量名到变量位置的映射
    functions: HashMap<String, (usize, usize)>,// 函数名到(函数地址, 参数数量)的映射
    classes: HashMap<String, ClassDefinition>, // 类名到类定义的映射
    next_var_index: i32,                     // 下一个变量的位置索引（全局变量从0开始，局部变量使用负数）
    current_line: usize,
    in_class: bool,
    current_class_name: String,
    function_bodies: HashMap<usize, (usize, usize)>, // 函数地址到(起始行, 结束行)的映射
    next_function_index: usize,
    pub source_map: HashMap<usize, usize>, // 指令位置到源代码行号的映射
    // 添加模块相关字段
    module_registry: ModuleRegistry,         // 模块注册表
    imported_modules: Vec<Module>,          // 已导入的模块列表
}

#[derive(Debug)]pub struct Function {
    bytecode: Vec<Instruction>,
    local_variables: HashMap<i32, Value>,
    arg_count: usize,
}

impl Function {
    // 默认预分配大小常量
    const DEFAULT_BYTECODE_CAPACITY: usize = 512;     // 预分配512条指令空间
    const DEFAULT_LOCAL_VARS_CAPACITY: usize = 32;    // 预分配32个局部变量空间
    
    /// 创建一个新的Function实例，预分配内存空间
    pub fn new(arg_count: usize) -> Self {
        Function {
            // 为字节码预分配空间
            bytecode: Vec::with_capacity(Self::DEFAULT_BYTECODE_CAPACITY),
            // 为局部变量（包括参数）预分配空间
            local_variables: HashMap::with_capacity(Self::DEFAULT_LOCAL_VARS_CAPACITY + arg_count),
            arg_count,
        }
    }
    
    /// 扩展字节码容量
    pub fn reserve_bytecode(&mut self, additional_capacity: usize) {
        self.bytecode.reserve(additional_capacity);
    }
    
    /// 扩展局部变量容量
    pub fn reserve_locals(&mut self, additional_capacity: usize) {
        self.local_variables.reserve(additional_capacity);
    }

    // 获取局部变量（包括参数）
    pub fn get_local(&self, index: i32) -> Option<&Value> {
        // 同时支持参数（负索引）和局部变量（正索引）
        self.local_variables.get(&index)
    }
    
    // 获取参数数量
    pub fn get_param_count(&self) -> usize {
        self.arg_count
    }
    
    // 设置局部变量
    pub fn set_local(&mut self, index: i32, value: Value) {
        self.local_variables.insert(index, value);
    }
    
    // 检查是否存在局部变量
    pub fn contains_local(&self, index: i32) -> bool {
        self.local_variables.contains_key(&index)
    }
}

impl Compiler {
    // 默认预分配大小常量
    const DEFAULT_BYTECODE_CAPACITY: usize = 1024;    // 预分配1024条指令空间
    const DEFAULT_MAP_CAPACITY: usize = 128;          // 预分配128个映射项
    const DEFAULT_MODULES_CAPACITY: usize = 16;       // 预分配16个模块空间
    
    pub fn new() -> Self {
        Compiler {
            // 为字节码预分配较大空间，减少动态扩容
            bytecode: Vec::with_capacity(Self::DEFAULT_BYTECODE_CAPACITY),
            // 为各种映射表预分配空间
            variables: HashMap::with_capacity(Self::DEFAULT_MAP_CAPACITY),
            functions: HashMap::with_capacity(Self::DEFAULT_MAP_CAPACITY),
            classes: HashMap::with_capacity(Self::DEFAULT_MAP_CAPACITY),
            next_var_index: 0,
            current_line: 0,
            in_class: false,
            current_class_name: String::new(),
            function_bodies: HashMap::with_capacity(Self::DEFAULT_MAP_CAPACITY),
            next_function_index: 0,
            source_map: HashMap::with_capacity(Self::DEFAULT_BYTECODE_CAPACITY),
            // 初始化模块相关字段
            module_registry: ModuleRegistry::new(),
            imported_modules: Vec::with_capacity(Self::DEFAULT_MODULES_CAPACITY),
        }
    }
    
    /// 重置编译器状态
    pub fn reset(&mut self) {
        self.bytecode.clear();
        self.variables.clear();
        self.functions.clear();
        self.classes.clear();
        self.next_var_index = 0;
        self.current_line = 0;
        self.in_class = false;
        self.current_class_name = String::new();
        self.function_bodies.clear();
        self.next_function_index = 0;
        self.source_map.clear();
        // 保留模块注册表，但清空已导入的模块
        self.imported_modules.clear();
    }
    
    // 创建使用特定模板的编译器
    pub fn with_template(_template: DestroyPoolTemplate) -> Self {
        // 这里保持原有的实现
        // 在实际使用模板时，可能需要根据模板调整预分配大小
        Self::new()
    }
    
    // 获取生成的字节码
    pub fn get_bytecode(&self) -> &[Instruction] {
        &self.bytecode
    }

    // 添加指令到字节码末尾
    pub fn append_instruction(&mut self, instruction: Instruction) {
        self.bytecode.push(instruction);
    }

    // 获取字节码的副本
    
    // 尝试在编译期评估常量表达式
    fn evaluate_constant_expression(&self, expr: &Box<ASTNode>) -> Option<Value> {
        match **expr {
            ASTNode::Literal(ref value) => Some(value.clone()),
            ASTNode::BinaryExpression(ref left, ref op, ref right) => {
                let left_val = self.evaluate_constant_expression(left);
                let right_val = self.evaluate_constant_expression(right);
                
                if let (Some(left_val), Some(right_val)) = (left_val, right_val) {
                    self.evaluate_binary_operation(&left_val, op, &right_val)
                } else {
                    None
                }
            },
            ASTNode::UnaryExpression(ref op, ref expr) => {
                if let Some(val) = self.evaluate_constant_expression(expr) {
                    match op {
                        Token::Minus => {
                            match val {
                                Value::Integer(i) => Some(Value::Integer(-i)),
                                Value::Float(f) => Some(Value::Float(-f)),
                                _ => None
                            }
                        },
                        Token::Not => {
                            match val {
                                Value::Boolean(b) => Some(Value::Boolean(!b)),
                                _ => None
                            }
                        },
                        _ => None
                    }
                } else {
                    None
                }
            },
            _ => None
        }
    }
    
    // 评估二元操作
    fn evaluate_binary_operation(&self, left: &Value, op: &Token, right: &Value) -> Option<Value> {
        use crate::types::TypeChecker;
        use std::sync::Arc;
        use crate::types::TypeEnvironment;
        
        let type_checker = TypeChecker::new(Arc::new(TypeEnvironment::new()));
        
        match op {
            Token::Plus => {
                match (left, right) {
                    (Value::Integer(a), Value::Integer(b)) => {
                        // 添加整数溢出检查
                        if let Some(result) = a.checked_add(*b) {
                            Some(Value::Integer(result))
                        } else {
                            None
                        }
                    },
                    (Value::Integer(a), Value::Float(b)) => Some(Value::Float(*a as f64 + *b)),
                    (Value::Float(a), Value::Integer(b)) => Some(Value::Float(*a + *b as f64)),
                    (Value::Float(a), Value::Float(b)) => Some(Value::Float(a + b)),
                    (Value::String(a), right_val) => {
                        if let Ok(converted) = type_checker.try_coerce_value(right_val.clone(), &crate::types::Type::String) {
                            if let Value::String(b) = converted {
                                return Some(Value::String(format!("{}{}", a, b)));
                            }
                        }
                        None
                    },
                    (left_val, Value::String(b)) => {
                        if let Ok(converted) = type_checker.try_coerce_value(left_val.clone(), &crate::types::Type::String) {
                            if let Value::String(a) = converted {
                                return Some(Value::String(format!("{}{}", a, b)));
                            }
                        }
                        None
                    },
                    (Value::Boolean(a), Value::Boolean(b)) => Some(Value::Boolean(*a || *b)), // 布尔加法作为逻辑或
                    _ => None
                }
            },
            Token::Minus => {
                match (left, right) {
                    (Value::Integer(a), Value::Integer(b)) => {
                        // 添加整数溢出检查
                        if let Some(result) = a.checked_sub(*b) {
                            Some(Value::Integer(result))
                        } else {
                            None
                        }
                    },
                    (Value::Integer(a), Value::Float(b)) => Some(Value::Float(*a as f64 - *b)),
                    (Value::Float(a), Value::Integer(b)) => Some(Value::Float(*a - *b as f64)),
                    (Value::Float(a), Value::Float(b)) => Some(Value::Float(a - b)),
                    _ => None
                }
            },
            Token::Multiply => {
                match (left, right) {
                    (Value::Integer(a), Value::Integer(b)) => {
                        // 添加整数溢出检查
                        if let Some(result) = a.checked_mul(*b) {
                            Some(Value::Integer(result))
                        } else {
                            None
                        }
                    },
                    (Value::Integer(a), Value::Float(b)) => Some(Value::Float(*a as f64 * *b)),
                    (Value::Float(a), Value::Integer(b)) => Some(Value::Float(*a * *b as f64)),
                    (Value::Float(a), Value::Float(b)) => Some(Value::Float(a * b)),
                    _ => None
                }
            },
            Token::Divide => {
                match (left, right) {
                    (Value::Integer(a), Value::Integer(b)) => {
                        if *b == 0 {
                            None
                        } else {
                            // 添加整数溢出检查
                            if let Some(result) = a.checked_div(*b) {
                                Some(Value::Integer(result))
                            } else {
                                None
                            }
                        }
                    },
                    (Value::Integer(a), Value::Float(b)) => {
                        if *b == 0.0 {
                            None
                        } else {
                            Some(Value::Float(*a as f64 / *b))
                        }
                    },
                    (Value::Float(a), Value::Integer(b)) => {
                        if *b == 0 {
                            None
                        } else {
                            Some(Value::Float(*a / *b as f64))
                        }
                    },
                    (Value::Float(a), Value::Float(b)) => {
                        if *b == 0.0 {
                            None
                        } else {
                            Some(Value::Float(a / b))
                        }
                    },
                    _ => None
                }
            },
            Token::Equal => {
                Some(Value::Boolean(left == right))
            },
            Token::NotEqual => {
                Some(Value::Boolean(left != right))
            },
            Token::Less => {
                match (left, right) {
                    (Value::Integer(a), Value::Integer(b)) => Some(Value::Boolean(a < b)),
                    (Value::Integer(a), Value::Float(b)) => Some(Value::Boolean((*a as f64) < *b)),
                    (Value::Float(a), Value::Integer(b)) => Some(Value::Boolean(*a < (*b as f64))),
                    (Value::Float(a), Value::Float(b)) => Some(Value::Boolean(a < b)),
                    (Value::String(a), Value::String(b)) => Some(Value::Boolean(a < b)),
                    _ => None
                }
            },
            Token::LessEqual => {
                match (left, right) {
                    (Value::Integer(a), Value::Integer(b)) => Some(Value::Boolean(a <= b)),
                    (Value::Integer(a), Value::Float(b)) => Some(Value::Boolean((*a as f64) <= *b)),
                    (Value::Float(a), Value::Integer(b)) => Some(Value::Boolean(*a <= (*b as f64))),
                    (Value::Float(a), Value::Float(b)) => Some(Value::Boolean(a <= b)),
                    (Value::String(a), Value::String(b)) => Some(Value::Boolean(a <= b)),
                    _ => None
                }
            },
            Token::Greater => {
                match (left, right) {
                    (Value::Integer(a), Value::Integer(b)) => Some(Value::Boolean(a > b)),
                    (Value::Integer(a), Value::Float(b)) => Some(Value::Boolean((*a as f64) > *b)),
                    (Value::Float(a), Value::Integer(b)) => Some(Value::Boolean(*a > (*b as f64))),
                    (Value::Float(a), Value::Float(b)) => Some(Value::Boolean(a > b)),
                    (Value::String(a), Value::String(b)) => Some(Value::Boolean(a > b)),
                    _ => None
                }
            },
            Token::GreaterEqual => {
                match (left, right) {
                    (Value::Integer(a), Value::Integer(b)) => Some(Value::Boolean(a >= b)),
                    (Value::Integer(a), Value::Float(b)) => Some(Value::Boolean((*a as f64) >= *b)),
                    (Value::Float(a), Value::Integer(b)) => Some(Value::Boolean(*a >= (*b as f64))),
                    (Value::Float(a), Value::Float(b)) => Some(Value::Boolean(a >= b)),
                    (Value::String(a), Value::String(b)) => Some(Value::Boolean(a >= b)),
                    _ => None
                }
            },
            Token::And => {
                match (left, right) {
                    (Value::Boolean(a), Value::Boolean(b)) => Some(Value::Boolean(*a && *b)),
                    _ => None
                }
            },
            Token::Or => {
                match (left, right) {
                    (Value::Boolean(a), Value::Boolean(b)) => Some(Value::Boolean(*a || *b)),
                    _ => None
                }
            },
            _ => None
        }
    }
    
    // 类型推测功能
    fn infer_type(&self, expr: &Box<ASTNode>) -> Option<crate::types::Type> {
        use crate::types::TypeChecker;
        use std::sync::Arc;
        use crate::types::TypeEnvironment;
        
        let type_checker = TypeChecker::new(Arc::new(TypeEnvironment::new()));
        
        match **expr {
            ASTNode::Literal(ref value) => {
                Some(type_checker.infer_type_from_value(value))
            },
            ASTNode::Identifier(ref _name) => {
                // 检查是否是常量或者已知类型的变量
                if let Some(const_value) = self.evaluate_constant_expression(expr) {
                    Some(type_checker.infer_type_from_value(&const_value))
                } else {
                    // 这里可以扩展为从变量表中查找变量类型
                    None
                }
            },
            ASTNode::BinaryExpression(ref left, ref op, ref right) => {
                // 对于可以在编译期求解的表达式，直接返回结果类型
                if let Some(result) = self.evaluate_constant_expression(expr) {
                    return Some(type_checker.infer_type_from_value(&result));
                }
                
                // 对于不能在编译期求解的表达式，尝试推测类型
                let left_type = self.infer_type(left);
                let right_type = self.infer_type(right);
                
                if let (Some(left_type), Some(right_type)) = (left_type, right_type) {
                    // 根据操作符和操作数类型推测结果类型
                    match op {
                        Token::Plus => {
                            if left_type == crate::types::Type::String || right_type == crate::types::Type::String {
                                Some(crate::types::Type::String)
                            } else if left_type == crate::types::Type::Float || right_type == crate::types::Type::Float {
                                Some(crate::types::Type::Float)
                            } else {
                                Some(crate::types::Type::Integer)
                            }
                        },
                        Token::Minus | Token::Multiply | Token::Divide => {
                            if left_type == crate::types::Type::Float || right_type == crate::types::Type::Float {
                                Some(crate::types::Type::Float)
                            } else {
                                Some(crate::types::Type::Integer)
                            }
                        },
                        Token::Equal | Token::NotEqual | Token::Less | Token::LessEqual | 
                        Token::Greater | Token::GreaterEqual | Token::And | Token::Or => {
                            Some(crate::types::Type::Boolean)
                        },
                        _ => None
                    }
                } else {
                    None
                }
            },
            _ => None
        }
    }
    pub fn get_bytecode_clone(&self) -> Vec<Instruction> {
        self.bytecode.clone()
    }

    // 获取已导入的模块
    pub fn get_module_registry(&self) -> &ModuleRegistry {
        &self.module_registry
    }
    
    /// 获取编译生成的函数信息
    /// 返回函数地址到参数数量的映射
    pub fn get_functions(&self) -> &HashMap<String, (usize, usize)> {
        &self.functions
    }
    
    // 导入模块
    fn import_module(&mut self, module_name: &str) -> Result<Module> {
        let module = match module_name {
            "core" => Ok(Module::Core),
            "io" => Ok(Module::IO),
            "math" => Ok(Module::Math),
            "string" => Ok(Module::String),
            "os" => Ok(Module::OS),
            "concurrent" => Ok(Module::Concurrent),
            "syscall" => Ok(Module::Syscall),
            _ => Err(PipitError::ModuleError(format!("Unknown module: {}", module_name))),
        }?;
        
        // 检查模块是否已经导入
        if !self.imported_modules.contains(&module) {
            self.imported_modules.push(module.clone());
            self.module_registry.load_module(module.clone())?;
        }
        
        Ok(module)
    }

    /// 编译源代码
    pub fn compile(&mut self, source: &str) -> Result<Vec<Instruction>> {
        if source.is_empty() {
            return Err(PipitError::CompileError("Cannot compile empty source".to_string()));
        }
        
        // 重置编译器状态
        self.bytecode.clear();
        self.variables.clear();
        self.functions.clear();
        self.classes.clear();
        self.next_var_index = 0;
        self.current_line = 0;
        self.source_map.clear();
        
        // 创建语法分析器并解析源代码
        let mut parser = Parser::new(source)?;
        let ast = parser.parse()?;
        
        // 从AST生成字节码
        self.generate_bytecode(&ast)?;
        
        // 添加程序结束指令
        self.bytecode.push(Instruction::Halt);
        
        // 修复：确保返回的是原始字节码，而不是可能被重复的副本
        Ok(self.bytecode.clone())
    }
    
    pub fn generate_bytecode(&mut self, ast: &Box<ASTNode>) -> Result<()> {
        // 修复字节码重复问题：在处理Program节点时，确保不会重复生成字节码
        if let ASTNode::Program(_) = &**ast {
            // 检查是否已经生成了字节码（通过查看bytecode是否为空）
            if !self.bytecode.is_empty() {
                // 如果已经生成了字节码，则直接返回
                return Ok(());
            }
        }
        
        match &**ast {
            ASTNode::Program(statements) => {
                // 两阶段编译策略：
                // 1. 收集所有函数定义（收集阶段）
                let mut function_definitions = Vec::new();
                let mut main_program_statements = Vec::new();
                
                for statement in statements {
                    if matches!(&**statement, ASTNode::FunctionDeclaration(_, _, _)) {
                        function_definitions.push(statement.clone());
                    } else {
                        main_program_statements.push(statement.clone());
                    }
                }
                
                // 2. 先记录所有函数信息，但不生成函数体字节码
                for func_def in &function_definitions {
                    if let ASTNode::FunctionDeclaration(name, params, _) = &**func_def {
                        // 使用next_function_index作为函数地址，确保从0开始分配
                        self.functions.insert(name.clone(), (self.next_function_index, params.len()));
                        // 暂时记录一个空的函数体范围
                        self.function_bodies.insert(self.next_function_index, (0, 0));
                        self.next_function_index += 1;
                    }
                }
                
                // 3. 先生成所有函数体的字节码（修复点：将这一步移到主程序字节码生成之前）
                for func_def in function_definitions {
                    if let ASTNode::FunctionDeclaration(name, params, body) = &*func_def {  // 修复1: 使用正确的解引用层级
                        // 获取函数地址
                        if let Some(&(func_addr, _)) = self.functions.get(name.as_str()) {  // 修复2: 使用as_str()
                            // 记录函数的实际字节码起始位置
                            let actual_func_start = self.bytecode.len();
                            
                            // 为参数分配局部变量索引（使用负索引）
                            let mut param_index = -1;
                            let original_vars = self.variables.clone(); // 保存原始变量表
                            let original_next_var = self.next_var_index;
                            
                            for param in params {
                                self.variables.insert(param.clone(), param_index);
                                param_index -= 1;
                            }
                            
                            // 生成函数体的字节码
                            self.generate_bytecode(&body)?;  // 修复3: 添加引用
                            
                            // 确保函数以Return指令结束
                            if let Some(last_instr) = self.bytecode.last() {
                                if !matches!(last_instr, Instruction::Return) {
                                    self.bytecode.push(Instruction::Return);
                                }
                            } else {
                                self.bytecode.push(Instruction::Return);
                            }
                            
                            // 更新函数体范围（使用函数地址作为键）
                            self.function_bodies.insert(func_addr, (actual_func_start, self.bytecode.len()));
                            
                            // 恢复原始变量表（避免函数参数污染全局作用域）
                            self.variables = original_vars;
                            self.next_var_index = original_next_var;
                        }
                    }
                }
                
                // 4. 最后生成主程序的字节码（包括函数调用）
                for statement in main_program_statements {
                    self.generate_bytecode(&statement)?;
                }
            },
            ASTNode::VariableDeclaration(name, expr) => {
                // 先生成表达式的字节码
                self.generate_bytecode(expr)?;
                
                // 为变量分配索引
                let var_index = self.next_var_index;
                self.variables.insert(name.clone(), var_index);
                self.next_var_index += 1;
                
                // 存储变量
                self.bytecode.push(Instruction::StoreVar(var_index));
            },
            ASTNode::AssignStatement(name, expr) => {
                // 先生成表达式的字节码
                self.generate_bytecode(expr)?;
                
                // 查找变量索引
                if let Some(&var_index) = self.variables.get(name) {
                    self.bytecode.push(Instruction::StoreVar(var_index));
                } else {
                    return Err(PipitError::CompileError(format!("Undefined variable: {}", name)));
                }
            },
            // 注意：这个分支只在函数不是作为Program的直接子节点时使用
            // 当函数是Program的直接子节点时，在Program处理的两阶段编译策略中已经处理过
            ASTNode::FunctionDeclaration(name, params, body) => {
                // 这种情况下，我们假设它是在块内部或其他上下文中定义的函数
                // 仍然需要正常处理
                
                // 记录函数起始位置
                let func_start = self.bytecode.len();
                
                // 记录函数信息
                self.functions.insert(name.clone(), (func_start, params.len()));
                
                // 为参数分配局部变量索引（使用负索引）
                let mut param_index = -1;
                let original_vars = self.variables.clone(); // 保存原始变量表
                let original_next_var = self.next_var_index;
                
                for param in params {
                    self.variables.insert(param.clone(), param_index);
                    param_index -= 1;
                }
                
                // 生成函数体的字节码
                self.generate_bytecode(body)?;
                
                // 确保函数以Return指令结束
                if let Some(last_instr) = self.bytecode.last() {
                    if !matches!(last_instr, Instruction::Return) {
                        self.bytecode.push(Instruction::Return);
                    }
                } else {
                    self.bytecode.push(Instruction::Return);
                }
                
                // 记录函数体范围
                self.function_bodies.insert(func_start, (func_start, self.bytecode.len()));
                
                // 恢复原始变量表（避免函数参数污染外部作用域）
                self.variables = original_vars;
                self.next_var_index = original_next_var;
            },
            ASTNode::FunctionCall(name, args) => {
                // 检查是否是内置函数或模块函数
                // 对于println和print这类IO函数，我们直接生成对应的指令
                if name == "println" {
                    // 为每个参数生成print指令
                    for (i, arg) in args.iter().enumerate() {
                        self.generate_bytecode(arg)?;
                        self.bytecode.push(Instruction::Print);
                        // 在参数之间添加空格（除了最后一个参数）
                        if i < args.len() - 1 {
                            self.bytecode.push(Instruction::Push(Value::String(" ".to_string())));
                            self.bytecode.push(Instruction::Print);
                        }
                    }
                    // 添加单独的换行，不使用Println指令（避免重复打印）
                    self.bytecode.push(Instruction::Push(Value::String("\n".to_string())));
                    self.bytecode.push(Instruction::Print);
                } else if name == "print" {
                    // 为每个参数生成print指令
                    for (i, arg) in args.iter().enumerate() {
                        self.generate_bytecode(arg)?;
                        self.bytecode.push(Instruction::Print);
                        // 在参数之间添加空格（除了最后一个参数）
                        if i < args.len() - 1 {
                            self.bytecode.push(Instruction::Push(Value::String(" ".to_string())));
                            self.bytecode.push(Instruction::Print);
                        }
                    }
                } else if name == "length" {
                    // 先生成参数的字节码
                    for arg in args {
                        self.generate_bytecode(arg)?;
                    }
                    // 数组长度函数
                    self.bytecode.push(Instruction::ArrayLength);
                } else if crate::stdlib_registry::is_stdlib_function(name) {
                    // 先生成参数的字节码
                    for arg in args {
                        self.generate_bytecode(arg)?;
                    }
                    // 标准库函数 - 生成NativeCall指令
                    self.bytecode.push(Instruction::NativeCall(name.clone()));
                } else {
                    // 先生成所有参数的字节码
                    for arg in args {
                        self.generate_bytecode(arg)?;
                    }
                    
                    // 添加函数调用指令
                    if let Some(&(func_addr, _arg_count)) = self.functions.get(name) {
                        self.bytecode.push(Instruction::Call(func_addr));
                    } else {
                        return Err(PipitError::CompileError(format!("Undefined function: {}", name)));
                    }
                }
            },
            ASTNode::ReturnStatement(expr) => {
                // 生成返回值表达式的字节码
                self.generate_bytecode(expr)?;
                // 添加返回指令
                self.bytecode.push(Instruction::Return);
            },
            ASTNode::IfStatement(condition, then_branch, else_branch) => {
                // 生成条件表达式的字节码
                self.generate_bytecode(condition)?;
                
                // 记录条件跳转指令的位置
                let cond_jump_pos = self.bytecode.len();
                // 添加条件跳转指令（目标地址暂时设为0）
                self.bytecode.push(Instruction::JumpIfFalse(0));
                
                // 生成then分支的字节码
                self.generate_bytecode(then_branch)?;
                
                // 记录then分支后的跳转指令位置
                let then_jump_pos = self.bytecode.len();
                // 添加无条件跳转指令（目标地址暂时设为0）
                self.bytecode.push(Instruction::Jump(0));
                
                // 更新条件跳转指令的目标地址（指向else分支或if语句结束）
                let else_start_pos = self.bytecode.len();
                if let Some(Instruction::JumpIfFalse(ref mut target)) = self.bytecode.get_mut(cond_jump_pos) {
                    *target = else_start_pos;
                }
                
                // 生成else分支的字节码（如果有）
                if let Some(else_body) = else_branch {
                    self.generate_bytecode(else_body)?;
                }
                
                // 更新then分支后的跳转指令的目标地址（指向if语句结束）
                let if_end_pos = self.bytecode.len();
                if let Some(Instruction::Jump(ref mut target)) = self.bytecode.get_mut(then_jump_pos) {
                    *target = if_end_pos;
                }
            },
            ASTNode::WhileStatement(condition, body) => {
                // 记录循环开始位置
                let loop_start_pos = self.bytecode.len();
                
                // 生成条件表达式的字节码
                self.generate_bytecode(condition)?;
                
                // 记录条件跳转指令的位置
                let cond_jump_pos = self.bytecode.len();
                // 添加条件跳转指令（目标地址暂时设为0）
                self.bytecode.push(Instruction::JumpIfFalse(0));
                
                // 生成循环体的字节码
                self.generate_bytecode(body)?;
                
                // 添加跳转到循环开始的指令
                self.bytecode.push(Instruction::Jump(loop_start_pos));
                
                // 更新条件跳转指令的目标地址（指向循环结束）
                let loop_end_pos = self.bytecode.len();
                if let Some(Instruction::JumpIfFalse(ref mut target)) = self.bytecode.get_mut(cond_jump_pos) {
                    *target = loop_end_pos;
                }
            },
            ASTNode::ForStatement(var_name, start, end, body) => {
                self.generate_bytecode(start)?;
                
                let var_index = self.next_var_index;
                self.variables.insert(var_name.clone(), var_index);
                self.next_var_index += 1;
                
                self.bytecode.push(Instruction::StoreVar(var_index));
                
                let loop_start_pos = self.bytecode.len();
                
                self.bytecode.push(Instruction::LoadVar(var_index));
                self.generate_bytecode(end)?;
                
                self.bytecode.push(Instruction::GreaterThan);
                
                let cond_jump_pos = self.bytecode.len();
                self.bytecode.push(Instruction::JumpIfTrue(0));
                
                self.generate_bytecode(body)?;
                
                self.bytecode.push(Instruction::LoadVar(var_index));
                self.bytecode.push(Instruction::Push(Value::Integer(1)));
                self.bytecode.push(Instruction::Add);
                self.bytecode.push(Instruction::StoreVar(var_index));
                
                self.bytecode.push(Instruction::Jump(loop_start_pos));
                
                let loop_end_pos = self.bytecode.len();
                if let Some(Instruction::JumpIfTrue(ref mut target)) = self.bytecode.get_mut(cond_jump_pos) {
                    *target = loop_end_pos;
                }
            },
            ASTNode::Block(statements) => {
                for statement in statements {
                    self.generate_bytecode(statement)?;
                }
            },
            ASTNode::BinaryExpression(left, op, right) => {
                // 对于空值合并运算符(??)，需要特殊处理
                if *op == Token::NullishCoalescing {
                    // 先生成左侧表达式的字节码
                    self.generate_bytecode(left)?;
                    
                    // 保存栈顶值(左侧表达式结果)到寄存器0
                    self.bytecode.push(Instruction::StackToRegister(0, 0));
                    
                    // 检查左侧值是否为null
                    self.bytecode.push(Instruction::RegLoadConst(1, Value::Null));
                    self.bytecode.push(Instruction::RegisterToStack(1));
                    self.bytecode.push(Instruction::RegisterToStack(0));
                    self.bytecode.push(Instruction::Equal);
                    
                    // 如果左侧是null，跳转到右侧表达式
                    let right_jump_pos = self.bytecode.len();
                    self.bytecode.push(Instruction::JumpIfTrue(0)); // 临时地址
                    
                    // 如果左侧不是null，直接使用左侧值
                    self.bytecode.push(Instruction::RegisterToStack(0));
                    
                    // 跳过右侧表达式
                    let end_jump_pos = self.bytecode.len();
                    self.bytecode.push(Instruction::Jump(0)); // 临时地址
                    
                    // 生成右侧表达式的字节码
                    let right_expr_start = self.bytecode.len();
                    if let Some(Instruction::JumpIfTrue(ref mut target)) = self.bytecode.get_mut(right_jump_pos) {
                        *target = right_expr_start;
                    }
                    self.generate_bytecode(right)?;
                    
                    // 更新结束跳转地址
                    let bytecode_len = self.bytecode.len();
                    if let Some(Instruction::Jump(ref mut target)) = self.bytecode.get_mut(end_jump_pos) {
                        *target = bytecode_len;
                    }
                } else {
                    // 尝试在编译期计算表达式的值
                    if let Some(const_value) = self.evaluate_constant_expression(&Box::new(ASTNode::BinaryExpression(left.clone(), op.clone(), right.clone()))) {
                        // 如果能够在编译期计算出结果，直接生成Push指令
                        self.bytecode.push(Instruction::Push(const_value));
                    } else {
                        // 处理其他二元操作符
                        self.generate_bytecode(left)?;
                        self.generate_bytecode(right)?;
                        
                        match op {
                            Token::Plus => self.bytecode.push(Instruction::Add),
                            Token::Minus => self.bytecode.push(Instruction::Sub),
                            Token::Multiply => self.bytecode.push(Instruction::Mul),
                            Token::Divide => self.bytecode.push(Instruction::Div),
                            Token::Equal => self.bytecode.push(Instruction::Equal),
                            Token::NotEqual => {
                                self.bytecode.push(Instruction::Equal);
                                self.bytecode.push(Instruction::Not);
                            },
                            Token::Less => self.bytecode.push(Instruction::LessThan),
                            Token::LessEqual => {
                                self.bytecode.push(Instruction::GreaterThan);
                                self.bytecode.push(Instruction::Not);
                            },
                            Token::Greater => self.bytecode.push(Instruction::GreaterThan),
                            Token::GreaterEqual => {
                                self.bytecode.push(Instruction::LessThan);
                                self.bytecode.push(Instruction::Not);
                            },
                            Token::And => self.bytecode.push(Instruction::And),
                            Token::Or => self.bytecode.push(Instruction::Or),
                            _ => return Err(PipitError::CompileError(format!("Unsupported operator: {:?}", op)))
                        }
                    }
                }
            },
            ASTNode::UnaryExpression(op, expr) => {
                // 尝试在编译期计算表达式的值
                if let Some(const_value) = self.evaluate_constant_expression(expr) {
                    // 如果能够在编译期计算出结果，直接生成Push指令
                    match op {
                        Token::Minus => {
                            match const_value {
                                Value::Integer(i) => self.bytecode.push(Instruction::Push(Value::Integer(-i))),
                                Value::Float(f) => self.bytecode.push(Instruction::Push(Value::Float(-f))),
                                _ => {
                                    // 对于不支持取负的类型，回退到运行时操作
                                    self.generate_bytecode(expr)?;
                                    self.bytecode.push(Instruction::RegLoadConst(0, Value::Integer(0)));
                                    self.bytecode.push(Instruction::RegisterToStack(0));
                                    self.bytecode.push(Instruction::Sub);
                                }
                            }
                        },
                        Token::Not => {
                            match const_value {
                                Value::Boolean(b) => self.bytecode.push(Instruction::Push(Value::Boolean(!b))),
                                _ => {
                                    // 对于不支持逻辑非的类型，回退到运行时操作
                                    self.generate_bytecode(expr)?;
                                    self.bytecode.push(Instruction::Not);
                                }
                            }
                        },
                        _ => {
                            // 生成表达式的字节码并应用操作符
                            self.generate_bytecode(expr)?;
                            return Err(PipitError::CompileError(format!("Unsupported unary operator: {:?}", op)));
                        }
                    }
                } else {
                    // 生成表达式的字节码
                    self.generate_bytecode(expr)?;
                    
                    // 根据操作符添加相应的指令
                    match op {
                        Token::Minus => {
                            // 使用 0 - value 来实现取反操作，使用寄存器暂存中间结果
                            self.bytecode.push(Instruction::RegLoadConst(0, Value::Integer(0))); // 加载0到寄存器0
                            self.bytecode.push(Instruction::RegisterToStack(0)); // 将0压入栈中
                            self.bytecode.push(Instruction::Sub); // 执行减法0-value
                        },
                        Token::Not => {
                            // 直接使用Not指令进行逻辑非操作
                            self.bytecode.push(Instruction::Not);
                        },
                        _ => return Err(PipitError::CompileError(format!("Unsupported unary operator: {:?}", op)))
                    }
                }
            },
            ASTNode::Identifier(name) => {
                // 检查是否可以在编译期获取变量值（如常量或已初始化的变量）
                // 对于可在编译期确定的变量值，直接push值而不是加载变量指令
                if let Some(const_value) = self.evaluate_constant_expression(&Box::new(ASTNode::Identifier(name.clone()))) {
                    self.bytecode.push(Instruction::Push(const_value));
                } else {
                    // 查找变量索引并加载变量
                    if let Some(&var_index) = self.variables.get(name) {
                        self.bytecode.push(Instruction::LoadVar(var_index));
                    } else {
                        return Err(PipitError::CompileError(format!("Undefined variable: {}", name)));
                    }
                }
            },
            ASTNode::Literal(value) => {
                // 将字面量压入栈
                self.bytecode.push(Instruction::Push(value.clone()));
            },
            ASTNode::ArrayLiteral(elements) => {
                let len = elements.len();
                // 生成所有元素的字节码
                for element in elements {
                    self.generate_bytecode(element)?;
                }
                
                // 创建数组
                self.bytecode.push(Instruction::MakeArray(len));
            },
            ASTNode::ArrayAccess(array, index) => {
                // 生成数组的字节码
                self.generate_bytecode(array)?;
                // 生成索引的字节码
                self.generate_bytecode(index)?;
                
                // 获取数组元素
                self.bytecode.push(Instruction::ArrayGet);
            },
            ASTNode::ArrayAssign(name, index, value) => {
                // 查找变量索引
                if let Some(&var_index) = self.variables.get(name) {
                    // 加载数组变量
                    self.bytecode.push(Instruction::LoadVar(var_index));
                    // 生成索引的字节码
                    self.generate_bytecode(index)?;
                    // 生成值的字节码
                    self.generate_bytecode(value)?;
                    
                    // 设置数组元素
                    self.bytecode.push(Instruction::ArraySet);
                } else {
                    return Err(PipitError::CompileError(format!("Undefined array variable: {}", name)));
                }
            },
            ASTNode::ClassDeclaration(name, methods, _fields) => {
                // 创建类定义
                let class_id = self.classes.len();
                let mut class_def = ClassDefinition::new(name.clone(), class_id);
                
                // 编译类方法
                for (method_name, params, body) in methods {
                    let method_start = self.bytecode.len();
                    
                    // 为参数分配局部变量索引
                    let mut param_index = -1;
                    for param in params {
                        self.variables.insert(param.clone(), param_index);
                        param_index -= 1;
                    }
                    
                    // 生成方法体的字节码
                    self.generate_bytecode(body)?;
                    
                    // 确保方法以Return指令结束
                    if let Some(last_instr) = self.bytecode.last() {
                        if !matches!(last_instr, Instruction::Return) {
                            self.bytecode.push(Instruction::Return);
                        }
                    }
                    
                    // 记录方法信息
                    class_def.methods.insert(method_name.clone(), (method_start, params.len()));
                }
                
                // 存储类定义
                self.classes.insert(name.clone(), class_def);
            },
            ASTNode::StructDeclaration(name, _fields, _defaults) => {
                // 结构体在运行时通过MakeStruct指令创建
                // 这里只记录结构体定义，实际创建在实例化时处理
                self.variables.insert(format!("struct_{}", name), self.next_var_index);
                self.next_var_index += 1;
            },
            ASTNode::ClassInstantiation(class_name, args) => {
                // 生成所有参数的字节码
                for arg in args {
                    self.generate_bytecode(arg)?;
                }
                
                // 创建类实例
                if let Some(class_def) = self.classes.get(class_name) {
                    self.bytecode.push(Instruction::MakeClass(class_def.class_id, args.len()));
                } else {
                    return Err(PipitError::CompileError(format!("Undefined class: {}", class_name)));
                }
            },
            // 可选链访问
            ASTNode::OptionalChainAccess(object, field) => {
                // 生成对象的字节码
                self.generate_bytecode(object)?;
                
                // 检查对象是否为null
                let null_check_pos = self.bytecode.len();
                self.bytecode.push(Instruction::JumpIfFalse(0)); // 临时地址
                
                // 如果不是null，获取字段
                self.bytecode.push(Instruction::StructGet(field.clone()));
                
                // 记录跳过null分支的跳转位置
                let null_skip_pos = self.bytecode.len();
                self.bytecode.push(Instruction::Jump(0)); // 临时地址
                
                // 如果是null，压入null值
                let null_handler_pos = self.bytecode.len();
                self.bytecode.push(Instruction::Push(Value::Null));
                
                // 更新跳转地址
                if let Some(Instruction::JumpIfFalse(ref mut target)) = self.bytecode.get_mut(null_check_pos) {
                    *target = null_handler_pos;
                }
                let bytecode_len = self.bytecode.len();
                if let Some(Instruction::Jump(ref mut target)) = self.bytecode.get_mut(null_skip_pos) {
                    *target = bytecode_len;
                }
            },
            // 可选链数组访问
            ASTNode::OptionalChainArrayAccess(object, index) => {
                // 生成对象的字节码
                self.generate_bytecode(object)?;
                
                // 检查对象是否为null
                let null_check_pos = self.bytecode.len();
                self.bytecode.push(Instruction::JumpIfFalse(0)); // 临时地址
                
                // 如果不是null，生成索引的字节码并获取数组元素
                self.generate_bytecode(index)?;
                self.bytecode.push(Instruction::ArrayGet);
                
                // 记录跳过null分支的跳转位置
                let null_skip_pos = self.bytecode.len();
                self.bytecode.push(Instruction::Jump(0)); // 临时地址
                
                // 如果是null，压入null值
                let null_handler_pos = self.bytecode.len();
                self.bytecode.push(Instruction::Push(Value::Null));
                
                // 更新跳转地址
                if let Some(Instruction::JumpIfFalse(ref mut target)) = self.bytecode.get_mut(null_check_pos) {
                    *target = null_handler_pos;
                }
                let bytecode_len = self.bytecode.len();
                if let Some(Instruction::Jump(ref mut target)) = self.bytecode.get_mut(null_skip_pos) {
                    *target = bytecode_len;
                }
            },
            ASTNode::StructLiteral(_struct_name, fields) => {
                // 生成所有字段值的字节码
                for (_, value) in fields {
                    self.generate_bytecode(value)?;
                }
                
                // 创建结构体
                self.bytecode.push(Instruction::MakeStruct(fields.len()));
            },
            ASTNode::StructAccess(expr, field) => {
                // 生成表达式的字节码
                self.generate_bytecode(expr)?;
                
                // 获取结构体字段
                self.bytecode.push(Instruction::StructGet(field.clone()));
            },
            ASTNode::StructAssign(struct_name, field, value) => {
                // 查找结构体变量
                if let Some(&var_index) = self.variables.get(struct_name) {
                    self.bytecode.push(Instruction::LoadVar(var_index));
                    self.generate_bytecode(value)?;
                    self.bytecode.push(Instruction::StructSet(field.clone()));
                } else {
                    return Err(PipitError::CompileError(format!("Undefined struct: {}", struct_name)));
                }
            },
            ASTNode::MethodCall(object, method, args) => {
                // 生成对象的字节码
                self.generate_bytecode(object)?;
                
                // 生成所有参数的字节码
                for arg in args {
                    self.generate_bytecode(arg)?;
                }
                
                // 调用方法
                self.bytecode.push(Instruction::CallMethod(method.clone(), args.len()));
            },
            ASTNode::GotoStatement(_label) => {
                // 跳转指令，需要后续处理标签位置
                self.bytecode.push(Instruction::Jump(0)); // 临时地址
            },
            ASTNode::LabelStatement(label) => {
                // 标签定义，记录标签位置
                let label_pos = self.bytecode.len();
                self.variables.insert(format!("label_{}", label), label_pos as i32);
            },
            ASTNode::TryStatement(try_block, catch_block, finally_block) => {
                // 记录catch块开始的位置（暂时设置为0，之后会更新）
                let try_begin_pos = self.bytecode.len();
                self.bytecode.push(Instruction::TryBegin(0));
                
                // 生成try块的字节码
                self.generate_bytecode(try_block)?;
                
                // 记录try块结束后跳转的位置
                let try_end_jump_pos = self.bytecode.len();
                self.bytecode.push(Instruction::Jump(0)); // 临时地址
                
                // 更新TryBegin指令的catch块位置参数
                let catch_begin_pos = self.bytecode.len();
                if let Some(Instruction::TryBegin(ref mut target)) = self.bytecode.get_mut(try_begin_pos) {
                    *target = catch_begin_pos;
                }
                
                // 处理catch块
                // 简化处理，假设catch_block是一个CatchBlock类型的节点
                self.generate_bytecode(catch_block)?;
                
                // 更新try块结束后的跳转地址，跳过catch块
                let after_catch_pos = self.bytecode.len();
                if let Some(Instruction::Jump(ref mut target)) = self.bytecode.get_mut(try_end_jump_pos) {
                    *target = after_catch_pos;
                }
                
                // 处理finally块（如果有）
                if let Some(finally_body) = finally_block {
                    // 记录finally之后的位置（暂时设置为0，之后会更新）
                    let finally_begin_pos = self.bytecode.len();
                    self.bytecode.push(Instruction::FinallyBegin(0));
                    
                    // 生成finally块的字节码
                    self.generate_bytecode(finally_body)?;
                    
                    // 更新FinallyBegin指令的after_pos参数
                    let after_finally_pos = self.bytecode.len();
                    if let Some(Instruction::FinallyBegin(ref mut target)) = self.bytecode.get_mut(finally_begin_pos) {
                        *target = after_finally_pos;
                    }
                    
                    // 生成FinallyEnd指令
                    self.bytecode.push(Instruction::FinallyEnd);
                }
                
                // 生成TryEnd指令
                self.bytecode.push(Instruction::TryEnd);
            },
            ASTNode::CatchStatement(param_name, body) => {
                // 通常在TryStatement中处理catch块
                // 这里为了完整性保留此节点处理
                // 传递0作为finally块的位置，表示没有finally块
                self.bytecode.push(Instruction::CatchBegin(0));
                
                // 为catch参数分配变量索引
                let param_index = self.next_var_index;
                self.variables.insert(param_name.clone(), param_index);
                self.next_var_index += 1;
                
                // 生成catch块的字节码
                self.generate_bytecode(body)?;
                
                self.bytecode.push(Instruction::CatchEnd);
            },
            ASTNode::ThrowStatement(expr) => {
                // 生成要抛出的表达式的字节码
                self.generate_bytecode(expr)?;
                
                // 生成Throw指令
                self.bytecode.push(Instruction::Throw);
            },
            ASTNode::ImportStatement(imports, module_path, alias) => {
                // 生成LoadModule指令加载模块
                self.bytecode.push(Instruction::LoadModule(module_path.clone()));
                
                // 处理导入的符号
                for import_name in imports {
                    // 使用导入名作为别名，如果没有提供别名的话
                    let import_alias = if let Some(ref a) = alias {
                        a.clone()
                    } else {
                        import_name.clone()
                    };
                    
                    // 生成ImportSymbol指令导入符号
                    self.bytecode.push(Instruction::ImportSymbol(import_name.clone(), import_alias.clone()));
                    
                    // 将导入的符号添加到变量表中
                    let var_index = self.next_var_index;
                    self.variables.insert(import_alias.clone(), var_index);
                    self.next_var_index += 1;
                }
            },
            ASTNode::ExportStatement(exports, module_name) => {
                // 处理导出的符号
                for export_name in exports {
                    // 使用导出名作为别名，如果没有提供模块名的话
                    let export_alias = if let Some(ref m) = module_name {
                        format!("{}.{}", m, export_name)
                    } else {
                        export_name.clone()
                    };
                    
                    // 生成ExportSymbol指令导出符号
                    self.bytecode.push(Instruction::ExportSymbol(export_name.clone(), export_alias.clone()));
                    
                    // 如果导出的符号在当前变量表中，确保它可以被访问
                    if !self.variables.contains_key(export_name.as_str()) {
                        self.variables.insert(export_name.clone(), self.next_var_index);
                        self.next_var_index += 1;
                    }
                }
            },
        }
        
        Ok(())
    }
}

// 导入新的前端和后端模块
use crate::frontend::{CompilerFrontend, SemanticAnalyzer};
use crate::backend::{CompilerBackend};
use crate::advanced_optimizations::{OptimizationLevel};

// 修复编译器文件结构

// 模块化编译器实现
// 这个实现使用CompilationPipeline来支持更模块化的编译流程
pub struct ModernCompiler {
    pipeline: crate::pipeline::CompilationPipeline,
}

impl ModernCompiler {
    pub fn new() -> Self {
        ModernCompiler {
            pipeline: crate::pipeline::CompilationPipeline::new(),
        }
    }
    
    // 使用模块化流水线编译源代码
    pub fn compile(&mut self, source: &str) -> Result<Vec<Instruction>> {
        self.pipeline.compile(source)
    }
    
    // 获取模块注册表
    pub fn get_module_registry(&self) -> &ModuleRegistry {
        self.pipeline.get_module_registry()
    }
    
    // 重置编译器状态
    pub fn reset(&mut self) {
        self.pipeline.reset()
    }
}

// 分离式编译器实现：明确分离前端和后端职责
pub struct SplitCompiler {
    frontend: CompilerFrontend,
    semantic_analyzer: SemanticAnalyzer,
    backend: CompilerBackend,
}

impl SplitCompiler {
    /// 创建新的分离式编译器
    /// optimization_level: 优化级别 (None, Basic, Medium, Aggressive)
    /// enable_jit: 是否启用JIT编译
    pub fn new(optimization_level: OptimizationLevel, enable_jit: bool) -> Self {
        SplitCompiler {
            frontend: CompilerFrontend::new(),
            semantic_analyzer: SemanticAnalyzer::new(),
            backend: CompilerBackend::new(optimization_level, enable_jit),
        }
    }
    
    /// 编译源代码，返回优化后的字节码
    pub fn compile(&mut self, source: &str) -> Result<Vec<Instruction>> {
        // 1. 前端：解析源代码生成AST
        let ast = self.frontend.parse(source)?;
        
        // 2. 语义分析：检查和优化AST
        let analyzed_ast = self.semantic_analyzer.analyze(ast)?;
        
        // 3. 后端：生成并优化字节码
        self.backend.generate_optimized_bytecode(analyzed_ast)
    }
    
    /// 仅执行词法分析，返回Token流
    pub fn tokenize(&mut self, source: &str) -> Result<Vec<Token>> {
        self.frontend.tokenize(source)
    }
    
    /// 获取后端引用，用于高级配置
    pub fn get_backend(&self) -> &CompilerBackend {
        &self.backend
    }
    
    /// 获取后端可变引用，用于高级配置
    pub fn get_backend_mut(&mut self) -> &mut CompilerBackend {
        &mut self.backend
    }
}